package com.kinghunt.misp.common.utils;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.kinghunt.misp.common.constant.ConfigHolder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class SmsClient {
    private final ConfigHolder configHolder;

    public SmsClient(ConfigHolder configHolder) {
        this.configHolder = configHolder;
    }

    @Async
    public void sendVerifyCode(String phoneNumber, String verifyCode) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", configHolder.getAccessKeyId(), configHolder.getAccessSecret());
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", configHolder.getSignName());
        request.putQueryParameter("TemplateCode", configHolder.getTemplateCode());
        Map<String, String> templateParam = new HashMap<>();
        templateParam.put("code", verifyCode);
        request.putQueryParameter("TemplateParam", JSON.toJSONString(templateParam));
        try {
            client.getCommonResponse(request);
        } catch (ClientException e) {
        }
    }
}
